﻿//### UTILITY FUNCTIONS ############################################

String.format = function(text)
{
    if (arguments.length <= 1)
        return text;

    var tokenCount = arguments.length - 2;
    for(var token = 0; token <= tokenCount; token++)
        text = text.replace(new RegExp( "\\{" + token + "\\}", "gi" ), arguments[ token + 1 ]);

    return text;
};


//### MEMBER VARIABLES #############################################

var chatPageWebPath = '';
var portalId = 0;
var clientHandlerUrl = '/DesktopModules/DNNspot-LiveSupport/ChatHandler.ashx';

var clientId = -1;
var email = '';
var firstName = '';
var ip = '';
var lastName = '';
var question = '';
var urlReferrer = '';
var userId = -1;
var maxMessagesPerSession = 999999;

var categoryId = -1;
var sessionId = -1;
var lastMessageId = -1;
var oldLastMessageId = lastMessageId;

//### HANDLER ACTIONS ##############################################

function closeSession() {
    if (sessionId > -1) {
        var postData = {};
        postData.Action = "CloseSession";

        postData.SessionId = sessionId;

        jQuery.post(
            clientHandlerUrl,
            postData,
            closeSessionCallback,
            'json'
        );

        sessionId = -1;
    }
}

function createSession() {
    var postData = {};
    postData.Action = "CreateSession";
    
    postData.PortalId = portalId;
    postData.UserId = userId;
    postData.Ip = ip;

    postData.ClientId = clientId;
    postData.FirstName = firstName;
    postData.LastName = lastName;
    postData.Email = email;
    postData.CategoryId = categoryId;
    postData.Question = question;
    postData.UrlReferrer = urlReferrer;

    var notes = "";

    jQuery('.custom').each(function() {
        var label = jQuery(this).prev('span.label');
        notes += String.format("{0}: {1}\n", label.text(), jQuery(this).val());
    });

    postData.Notes = notes;

    jQuery.post(
        clientHandlerUrl,
        postData,
        createSessionCallback,
        'json'
    );
}

function getSessionState() {
    var postData = {};
    postData.Action = 'GetSessionState';
    postData.PortalId = portalId;
    postData.SessionId = sessionId;
    postData.MessageId = lastMessageId;

    jQuery.post(
        clientHandlerUrl,
        postData,
        getSessionStateCallback,
        'json'
    );
}

function postMessage(messageBody, system) {
    var postData = {};
    postData.Action = 'PostMessage';
    postData.PortalId = portalId;
    postData.SessionId = sessionId;
    postData.MessageBody = messageBody;
    postData.MaxMessagesPerSession = maxMessagesPerSession;

    if (system != true)
        postData.ClientId = clientId;

    jQuery.post(
        clientHandlerUrl,
        postData,
        postMessageCallback,
        'json'
    );
}

//### HANDLER CALLBACKS ############################################

function closeSessionCallback(data) {
    if (data.Success) {
        var currentIndex = selectTabBySessionId(data.SessionId);
        jQuery('#divTabs').tabs('remove', currentIndex);
    }
}

function createSessionCallback(data) {
    if (data.success) {
        sessionId = data.SessionId;
        setClientId(data.ClientId);
        hidePrerequisites();

        getSessionState();
    }
}

function getSessionStateCallback(data) {
    jQuery(data.Messages).each(appendMessages);

    lastMessageId = data.LastMessageId;

    if (oldLastMessageId != lastMessageId) {
        oldLastMessageId = lastMessageId;
        jQuery('#divTranscript').scrollTo('100%', 0);
    }
    
    getSessionState();
}

function postMessageCallback(data) {
    
}

//### METHODS ######################################################

function appendMessages(i, obj) {
    var msgCount = jQuery('.message').length;
    
    if (obj.MessageId > lastMessageId) {
        var msg = String.format('<div class="message{0}{1}"><div class="name">{2}</div><div class="body">{3}</div></div>',
        msgCount % 2 == 0 ? '' : ' alt',
        obj.AgentId == null ? (obj.ClientId == null ? ' system' : ' self') : '',
		obj.Name != null ? String.format('{0}:', obj.Name) : '',
		obj.Body);

        jQuery('#divTranscript').append(msg).autolink();
    }
}

function applyLayout() {
    jQuery('body').layout({
        applyDefaultStyles: true,
        south__closable: false,
        south__resizable: false,
        south__size: 75
    });
}

function loadSettings() {
    chatPageWebPath = String.format('{0}ChatHandler.ashx', jQuery('#hidChatPageWebPath').val());
    clientId = parseInt(jQuery('#hidClientId').val());
    email = jQuery('#hidEmail').val();
    firstName = jQuery('#hidFirstName').val();
    ip = jQuery('#hidIp').val();
    lastName = jQuery('#hidLastName').val();
    portalId = parseInt(jQuery('#hidPortalId').val());
    userId = parseInt(jQuery('#hidUserId').val());
    urlReferrer = jQuery('#hidUrlReferrer').val();

    jQuery('#txtEmail').val(email);
    jQuery('#txtFirstName').val(firstName);
    jQuery('#txtLastName').val(lastName);
}

function setClientId(id) {
    clientId = id;
    jQuery.cookie('DNNspotLiveChatClientId', clientId);
}

function setupPersistentLogin() {
    setInterval('jQuery("#persistentLogin").attr("src", "/");', 1000 * 60 * 5);
}

function setupPrerequisiteValidation() {
    jQuery('#divQuestions').validationEngine();
}

function showPrerequisites() {
    jQuery('#divQuestions').show();
    jQuery('body').block({
        message: jQuery('#divQuestions'),
        css: {
            cursor: 'default',
            padding: '10px',
            textAlign: 'left',
            width: '80%',
            '-moz-border-radius': '10px',
            '-webkit-border-radius': '10px'
        },
        overlayCSS: {
            cursor: 'default'
        }
    });
}

function hidePrerequisites() {
    jQuery('body').unblock();

    jQuery('#ddlCategories').hide();
    jQuery('.custom').hide();
    jQuery('#divQuestions').hide();
    
    jQuery('#txtInput').focus();
}

//### BINDINGS #####################################################

function btnContinue_Click() {
    if (jQuery("#divQuestions").validationEngine({ returnIsValid: true })) {
        firstName = jQuery('#txtFirstName').val();
        lastName = jQuery('#txtLastName').val();
        email = jQuery('#txtEmail').val();
        categoryId = jQuery('#ddlCategories').val();
        question = jQuery('#txtQuestion').val();
        
        createSession();
    }
}

function txtInput_KeyPress(e) {
    if (e.keyCode == 13) {
        e.stopPropagation();
        e.preventDefault();

        if (jQuery('#txtInput').val() != '') {
            postMessage(jQuery('#txtInput').val());
            jQuery('#txtInput').val('');
        }
    }
}

//### PAGE LOAD ####################################################

jQuery(function () {
    applyLayout();
    setupPrerequisiteValidation();
    showPrerequisites();
    setupPersistentLogin();

    loadSettings();

    window.onbeforeunload = function () { closeSession(); };
    window.onunload = function () { closeSession(); };
    jQuery(window).unload(function () { closeSession(); });

    // Setup bindings
    jQuery('#btnContinue').click(btnContinue_Click);
    jQuery('#txtInput').keypress(txtInput_KeyPress);
});